<template>
  <div class="login-account">
    <el-form label-width="60px" :rules="rules" :model="info" ref="formRef">
      <el-form-item label="账号" prop="zh">
        <el-input v-model="info.zh" placeholder="coderwhy" />
      </el-form-item>
      <el-form-item label="密码" prop="mm">
        <el-input v-model="info.mm" show-password placeholder="123456" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { rules } from '../config/account-config'
import { useStore } from 'vuex'
import { ElForm } from 'element-plus'
import LocalCache from '@/utils/cache'

export default defineComponent({
  setup() {
    const info = reactive({
      zh: LocalCache.getCache('zh') ?? '',
      mm: LocalCache.getCache('mm') ?? ''
    })
    // 规则在config文件中

    // ref的类型是InstanceType<typeof ElForm>时,里面包含了对elfrom的类型判断
    // InstanceType: 实例类型,要传入组件实例
    const formRef = ref<InstanceType<typeof ElForm>>()
    const store = useStore()

    const loginAction = (isRememberMm: boolean) => {
      formRef.value?.validate((valid) => {
        if (valid) {
          // 1.是否记住密码
          if (isRememberMm) {
            //本地缓存
            LocalCache.setCache('zh', info.zh)
            LocalCache.setCache('mm', info.mm)
          } else {
            LocalCache.removeCache('zh')
            LocalCache.removeCache('mm')
          }
          // 2.登录验证
          store.dispatch('login/accountLoginAction', { ...info })
        }
      })
    }
    return {
      info,
      // 导入之后必须return
      rules,
      loginAction,
      formRef
    }
  }
})
</script>

<style scoped lang="less"></style>
